package com.zy.scwwebuis.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zy.scwcommon.bean.AppResponse;
import com.zy.scwwebuis.config.AlipayConfig;
import com.zy.scwwebuis.service.TOrderServiceFeign;
import com.zy.scwwebuis.vo.req.OrderFormInfoSubmitVo;
import com.zy.scwwebuis.vo.req.OrderInfoSubmitVo;
import com.zy.scwwebuis.vo.resp.ReturnPayConfirmVo;
import com.zy.scwwebuis.vo.resp.TOrder;
import com.zy.scwwebuis.vo.resp.UserRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
* @program: zyzc_springcloud
*
* @description: 远程调用订单模块
*
* @author: ZYY
*
* @create: 2024-07-19 11:44
**/
@Slf4j
@Controller
public class OrderController {
	@Autowired
	TOrderServiceFeign tOrderServiceFeign;
	@Autowired
	RedisTemplate redisTemplate;
		/**
		 * @Description:生成订单号--------重定向到支付页面
		 * @Param:  /templates/member/pay
		 * @return:
		 * @Author: zy
		 * @Date:
		 */
	@ResponseBody
	@RequestMapping("/order/pay")
	public String pay(OrderFormInfoSubmitVo orderFormInfoSubmitVo, HttpSession session){
		log.debug("提交订单立即支付----OrderFormInfoSubmitVo={}",orderFormInfoSubmitVo);
		//1.下单
		//把form的信息转换成提交的对象vo
		OrderInfoSubmitVo submitVo = new OrderInfoSubmitVo();
		BeanUtils.copyProperties(orderFormInfoSubmitVo,submitVo);//对象数据对拷贝

		UserRespVo userRespVo  = (UserRespVo)session.getAttribute("loginMember");
		if(userRespVo==null){
			return "redirect:/login ";
		}
		String accessToken = userRespVo.getAccessToken();
		submitVo.setAccessToken(accessToken);
		ReturnPayConfirmVo returnPayConfirmVo = (ReturnPayConfirmVo) session.getAttribute("returnPayConfirmVoSession");
		if(returnPayConfirmVo==null){
			return "redirect:/login ";
		}
		submitVo.setProjectid(returnPayConfirmVo.getProjectId());
		submitVo.setReturnid(returnPayConfirmVo.getReturnId());
		submitVo.setRtncount(returnPayConfirmVo.getNum());

		AppResponse<TOrder> orderAppResponse = tOrderServiceFeign.saveOrder(submitVo);
		TOrder order = orderAppResponse.getData();
		log.debug("订单的详细信息========{}",order);
		//2.支付   TODO FFFF
		String orderName = returnPayConfirmVo.getProjectName();
		//调用支付宝需要传入的参数
		String result = payOrder(order.getOrdernum(), order.getMoney(),orderName,submitVo.getRemark());
		//return "redirect:/member/minecrowdfunding";
		return result ; // 这是一个表单，返回给浏览器，并且立即提交表单，出来二维码支付页面
	}

	private String payOrder(String ordernum, Integer money, String orderName, String remark) {
		try {
			//获得初始化的AlipayClient
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

			//设置请求参数
			AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
			alipayRequest.setReturnUrl(AlipayConfig.return_url);
			alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


			alipayRequest.setBizContent("{\"out_trade_no\":\""+ ordernum +"\","
					+ "\"total_amount\":\""+ money +"\","
					+ "\"subject\":\""+ orderName +"\","
					+ "\"body\":\""+ remark +"\","
					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

			String result = alipayClient.pageExecute(alipayRequest).getBody();
			return result ;
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return null ;
		}
	}
	//临时写在客户端，正常应该写在订单服务系统中。  需要内网穿透。
	@ResponseBody
	@RequestMapping("/order/updateOrderStatus")
	public String updateOrderStatus() {

		// request.getParameterMap();
		log.debug("支付宝支付完成后，异步通知结果....");

		return "success";  //业务完成，必须返回"success"字符串给支付宝服务器，表示交易完成。
	}

}

